const DB_NAME = 'my-db'
let db = null
const cb = []

const format = (_) => _ && JSON.parse(JSON.stringify(_))
const createLibrary = () => {
  const o = db.createObjectStore('library', { keyPath: 'id', autoIncrement: true })
  o.createIndex('path', 'path', { unique: true })
}

const createGame = () => {
  const o = db.createObjectStore('game', { keyPath: 'id', autoIncrement: true })
  o.createIndex('file', ['path', 'name'], { unique: true })
  o.createIndex('path', 'path', { unique: false })
}

const createApp = () => {
  const o = db.createObjectStore('app', { keyPath: 'id', autoIncrement: true })
  o.createIndex('path', 'path', { unique: true })
}

const createPath = () => {
  const o = db.createObjectStore('path', { keyPath: 'id', autoIncrement: true })
  o.createIndex('path', 'path', { unique: true })
}

const create = () => {
  const request = window.indexedDB.open(DB_NAME, 2)
  request.onerror = function () {
    console.log('数据库打开报错')
  }
  request.onsuccess = function () {
    db = request.result
    cb.map((_) => _())
    console.log('数据库打开成功')
  }
  request.onupgradeneeded = function (event) {
    db = event.target.result
    createPath()
    // createLibrary()
    // createGame()
    // createApp()
  }
}

const promise = (action, key, value) => {
  return new Promise((resolve, reject) => {
    const fn = () => {
      let objectStore = db.transaction([key], 'readwrite').objectStore(key)
      let e = null
      if (action === 'index') {
        const [k, v] = Object.entries(value)
        e = objectStore.index(k)
        e = e.get(v)
      } else e = objectStore[action](value)
      e.onsuccess = function (e) {
        resolve(e.target.result)
      }
      e.onerror = function (e) {
        // console.error(key, value, e.target.error)
        reject()
      }
    }
    db ? fn() : cb.push(fn)
  })
}

create()
export const add = (...arg) => promise('add', ...format(arg))
export const del = (...arg) => promise('delete', ...format(arg))
export const set = (...arg) => promise('put', ...format(arg))
export const get = (...arg) => promise(arg[1] ? 'get' : 'getAll', ...format(arg))
export const getByIndex = (...arg) => promise('index', ...format(arg))
export const getList = (key, check) =>
  new Promise((resolve, reject) => {
    const fn = () => {
      let objectStore = db.transaction([key], 'readonly').objectStore(key)
      const e = objectStore.openCursor()
      let list = []
      e.onsuccess = (event) => {
        const cursor = event.target.result
        if (cursor) {
          check(cursor.value) && list.push(cursor.value)
          cursor.continue()
        } else {
          resolve(list)
        }
      }
      // e.onerror = function (e) {
      //   console.error(key, e.target.error)
      //   reject()
      // }
    }
    db ? fn() : cb.push(fn)
  })
